import router from '@/router'
import { useUserStore } from '@/stores'
import axios, { type Method } from 'axios'
import { ElMessage } from 'element-plus'
console.log(import.meta.env.VITE_APP_BASE_API,'11'); // 输出: https://consult-api.itheima.net/

const instance = axios.create({
  // TODO 1. 基础地址，超时时间
  baseURL:import.meta.env.VITE_APP_BASE_API,
  timeout: 10000
})

instance.interceptors.request.use(
  (config) => {
    // TODO 2. 携带token
    const store = useUserStore()
    if (store.user?.token || config.headers) {
      config.headers['Authorization'] = `Bearer ${store.user?.token}`
    }
    return config
  },
  (err) => Promise.reject(err)
)

instance.interceptors.response.use(
  (res) => {
    // 后台约定，响应成功，但是code不是10000，是业务逻辑失败
    if (res.data?.code !== 10000) {
      ElMessage(res.data?.message || '业务失败')
      return Promise.reject(res.data)
    }
    return res.data
  },
  (err) => {
    // TODO 5. 处理401错误
    if (err.response.status === 401) {
      // 删除用户信息
      const store = useUserStore()
      store.delUser()
      // 跳转登录
      router.push({
        path: '/login',
        query: { returnUrl: router.currentRoute.value.fullPath }
      })
    }
    return Promise.reject(err)
  }
)

export default instance

type Data<T> = {
  code: number
  message: string
  data: T
}

export const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  // 参数：地址，请求方式，提交的数据
  // 返回：promise
  return instance.request<any, Data<T>>({
    url,
    method,
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData
  })
}
